package com.gree.shyun.server.mail;

import com.gree.shyun.server.db.util.LogUtils;
import org.apache.commons.logging.Log;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 生成邮件工具类
 */
public class EmailSender {

    private String host;
    private String account;
    private String password;
    private String port;
    private final String charset = "UTF-8";
    private final String htmlCharset = "text/html;charset=UTF-8";
    private static Map<String, EmailSender> instances = new HashMap<String, EmailSender>();

    public EmailSender(){}

    private EmailSender(String port, String account, String password, String host){
        this.host = host;
        this.account = account;
        this.password = password;
        this.port = port;
    }

    /**
     * 默认账号
     * @return
     */
    public static EmailSender get() {
        String port = "25";
        String account ="通知公告<youdelu@163.com>";
        String password="WMNDOGWXJMVWHSLA";
        String host ="smtp.163.com";
        if (!instances.containsKey(account)) {
            instances.put(account, new EmailSender(port, account, password,host));
        }
        return instances.get(account);
    }

    public static EmailSender getInstance(String port, String account, String password, String host) {
        if (!instances.containsKey(account)) {
            instances.put(account, new EmailSender(port, account, password,host));
        }
        return instances.get(account);
    }

    private Session getSession(final String address) {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host); // 新浪smtp服务 "smtp.sina.cn"
        properties.setProperty("mail.smtp.auth","true");
        if ("465".equalsIgnoreCase(port)) {
            properties.put("mail.smtp.socketFactory.port", "465");
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.port", "465");
        } else {
            properties.put("mail.smtp.port", port);
        }

        return Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(address,password);
                }
        });
    }

    private InternetAddress parseInternetAddress(String address) throws AddressException, UnsupportedEncodingException {
        InternetAddress actual;
        if ((address.contains("<")) && (address.contains(">"))) {
            String email = address.substring(address.indexOf("<") + 1, address.indexOf(">"));
            String personal = address.substring(0, address.indexOf("<"));
            actual = new InternetAddress(email, personal, charset);
        } else {
            actual = new InternetAddress(address);
        }
        return actual;
    }



    public void send(String title,String context){
        send(title,context,null);
    }
    public void send(String title,String context,String[] filePath){
        EmailModel emailModel = new EmailModel(title,context,filePath,"游德禄<762283780@qq.com>;");
        send(emailModel);
    }


    public void send(EmailModel model) {
        this.floorSendContext(model);
    }

    // 发送文本邮件底层实现方法
    private void floorSendContext(EmailModel model) {
        try{

            final InternetAddress sender = parseInternetAddress(account);
            Session session = getSession(sender.getAddress());
            // 创建MinmeMessage对象
            MimeMessage message = new MimeMessage(session);
            message.setSentDate(new Date());
            // 设置发件人
            message.setFrom(sender);
            String[] mailToArrays = model.getMailTo().split(";");
            InternetAddress[] toAddress = new InternetAddress[mailToArrays.length];
            for (int i = 0;i<mailToArrays.length;i++) {
                toAddress[i] = parseInternetAddress(mailToArrays[i]);
            }
            // 设置收件人(多个或单个)
            message.addRecipients(Message.RecipientType.TO,toAddress);
            // 设置邮件标题
            message.setSubject(model.getSubjectTitle(),charset);
            MimeMultipart multipart = new MimeMultipart();
            //创建文本节点
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(model.getSubjectContxt(),htmlCharset);
            multipart.addBodyPart(text);

            if(model.getFilePath()!=null&&model.getFilePath().length>0) {
                //添加文件
                for (String path : model.getFilePath()) {
                    File f = new File(path);
                    if (f.exists()) {
                        MimeBodyPart file = new MimeBodyPart();
                        DataHandler dataHandler = new DataHandler(new FileDataSource(path));
                        file.setDataHandler(dataHandler);
                        file.setFileName(MimeUtility.encodeText(dataHandler.getName()));
                        multipart.addBodyPart(file);
                    }
                }
            }
            multipart.setSubType("mixed");//混合关系
            message.setContent(multipart);
            message.saveChanges();

            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            // 发送
            Transport.send(message);
            System.out.println("["+Calendar.getInstance().getTime().toLocaleString()+"]: 邮件发送成功。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
